<?php
namespace app\common\logic;

use think\Model;
use think\Loader;
use app\common\validate\CategoryValidate;
use app\common\model\Category as CategoryModel;

class Category extends Model
{
    const SPACE = "\xe3\x80\x80\xe3\x80\x80";

    /**
     * 获取分类列表
     *
     * @param $map array 查询条件
     * @param $model string 使用模型 (匹配不到该模型，当前分类disabled禁用表示)
     * @param $category_id int 分类ID (如果匹配到列表中 增加select选中表示)
     * @return array
     */
    public function getList($map = array(), $model = '', $category_id = '')
    {
        $list = CategoryModel::getList($map, 'reorder desc,id desc', 99999);
        $data = array();
        if (is_array($list)) {
            foreach ($list as $v) {
                $v['mode'] = $v['type'] == 1 ? '封面模式' : '列表模式';

                if (! empty($model)) {
                    // 禁用标识
                    $v['disabled'] = $v['type'] == 1 || $v['table_name'] != $model ? 'disabled' : '';
                }

                if (! empty($category_id)) {
                    // 选中标识
                    $v['selected'] = $category_id == $v['id'] ? 'selected' : '';
                }

                array_push($data, $v);
            }
        }

        return unlimitedForLevel($data, $html = self::SPACE, $root = 0, $levle = 0);
    }

    /*
     * 创建保存栏目信息
     * @params $data array
     * @return mix
    */
    public function add($data)
    {
        $validate = Loader::validate('CategoryValidate');
        $result = $validate->scene('add')->check($data);
        if (!$result) {
            return $validate->getError();
        }
        return CategoryModel::add($data);
    }

    public function edit($data)
    {
        $validate = Loader::validate('CategoryValidate');
        $result = $validate->scene('edit')->check($data);
        if (!$result) {
            return $validate->getError();
        }
        return CategoryModel::edit($data);
    }
}